package GoodsService

import (
	"database/sql"
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/app/service/BaseService"
	"gdshop-admin-go-api/app/service/CategoryService"
	"gdshop-admin-go-api/library/response"
	"gdshop-admin-go-api/library/tools"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"strings"
)

func GetListTypeWhere(listTypeInt int, condition g.Map) {
	switch listTypeInt {
	case 3:
		condition["g.status"] = 0
		break
	case 2:
		condition["g.status"] = 1
		condition["g.stock < ?"] = 1
		break
	case 1:
		condition["g.status"] = 1
		condition["g.stock > ?"] = 0
		break
	}
}

func Page(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	condition := g.Map{}
	obj := toolsDb.GetUnSafaTable(ctx, req.TableName)
	countObj := toolsDb.GetUnSafaTable(ctx, req.TableName)
	// 默认全部表别名先设置为 a
	asName := "a"
	// 处理查询的列
	selectFields := ""
	defaultSelectFields := strings.Split(obj.GetFieldsStr(), ",")

	pageQueryOp := req.PageQueryOp
	if pageQueryOp != nil {
		if pageQueryOp.AsName != "" {
			asName = pageQueryOp.AsName
		}
	}
	// 有设置表别名
	obj.As(asName)
	countObj.As(asName)
	// 获取查询条件
	BaseService.GetCondition(r, condition, pageQueryOp, asName)

	GetListTypeWhere(r.GetInt("list_type", 1), condition)

	obj.Where(
		condition,
	)
	countObj.Where(
		condition,
	)

	if pageQueryOp != nil {
		if len(pageQueryOp.SelectFields) > 0 {
			// 设置了 select 的
			selectFields = strings.Join(pageQueryOp.SelectFields, ",")
		}
		if pageQueryOp.OrderBy != "" {
			obj.Order(pageQueryOp.OrderBy)
		}
	}
	// 设置 select
	if selectFields != "" {
		obj.Fields(selectFields)
	} else {
		for k, v := range defaultSelectFields {
			defaultSelectFields[k] = asName + "." + v
		}
		obj.Fields(strings.Join(defaultSelectFields, ","))
	}
	// 处理查询里 --- end ---
	// 设置 删除时间
	obj.Where(asName + ".delete_at < 1")
	countObj.Fields("1").Where(asName + ".delete_at < 1")

	if pageQueryOp != nil {
		for _, item := range pageQueryOp.LeftJoin {
			obj.LeftJoin(item.TableInfo, item.Condition)
			countObj.LeftJoin(item.TableInfo, item.Condition)
		}
	}
	selectIds := r.GetStrings("selectids")
	if len(selectIds) > 0 {
		countObj.Where(asName+".id IN (?)", selectIds)
		obj.Where(asName+".id IN (?)", selectIds)
	}
	selectSql := r.GetString("select_sql")
	if len(selectSql) > 0 {
		countObj.Where(asName + ".id IN (" + selectSql + ")")
		obj.Where(asName + ".id IN (" + selectSql + ")")
	}

	count, countErr := countObj.Count()
	if countErr != nil {
		return response.FailByRequestMessage(nil, countErr.Error())
	}
	res, err := obj.Page(req.Page, req.PageSize).All()
	if err != nil {
		if err != sql.ErrNoRows {
			// 非 结果为空
			return response.FailByRequestMessage(nil, err.Error())
		}
	}
	resList := res.List()
	// 先取出分类
	cateArr, err := CategoryService.GetCategoryArrayType(ctx, "shop")
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	resList = GoodsPageHandle(cateArr, resList)
	/*for _, item := range resList {
		if item["store_id"] == 0 {
			item["store_name"] = "自营"
		}
		// 取出分类信息
		item["cates_text"] = tools.GetGoodsCatesText(gconv.String(item["cates"]), cateArr)

		delete(item, "cates")
		delete(item, "stock_cnf")
		delete(item, "delete_at")
	}*/
	return response.SuccessByRequestMessageData(nil, "获取成功",
		g.Map{
			"list":       resList,
			"pagination": tools.GetPageInfo(count, req.Page, req.PageSize),
		})
}

func GoodsPageHandle(cateArr g.Map, resList g.List) g.List {
	for _, item := range resList {
		if item["store_id"] == 0 {
			item["store_name"] = "自营"
		}
		// 取出分类信息
		item["cates_text"] = tools.GetGoodsCatesText(gconv.String(item["cates"]), cateArr)

		delete(item, "cates")
		delete(item, "stock_cnf")
		delete(item, "delete_at")
	}

	return resList
}
